After we have tinkered with general plotting in R, and before we learn from other plotting methods using ggplot2, we now conclude our session with programmatically playing with plots. In the previous exercise, we had some repeated tasks to perform. Maybe we can find a more elegant way of creating multiple plots.

Make sure our GESIS Panel COVID-19 data are loaded:

library(dplyr)
library(haven)

gp_covid <- 
  read_sav(
    "../data/ZA5667_v1-1-0.sav"
  ) %>% 
  sjlabelled::set_na(na = c(-1:-99, 97))

1

Write a function that automatically creates a table of an input variable and feeds it into a barplot. Moreover, provide an interface to enter the variable name as a character string and the dataset separately by including two commands in the function call.
After the function call, use two function arguments with function (variable, data) and call the variable within the function with data[[variable]].
barplotter <- function (variable, data) {
  barplot(table(data[[variable]]))
}

barplotter("hzcy001a", gp_covid)

Pew, that was not about plotting but rather about programming (sorry!). But now you can use this function and include it in a loop!

2

Take all four variables from the previous exercise session and feed them in a loop that calls the plotting function. You may want again call par() before the loop to have all variables nicely plotted in one graph.
Define a character vector with the variable names before you build your graph. For the loop, I’d suggest using a for() loop, which iterates over this character vector.
variable_names <- c("hzcy001a", "hzcy002a", "hzcy003a", "hzcy004a")

par(mfrow = c(2, 2))
for (variable in variable_names) {
  barplotter(variable, gp_covid)
}

Before we later start with the other exercises, you may want to consider to clean your graphics device with dev.off()

dev.off()
## null device 
##           1